<template>
  <div class="member-container">
    <div class="member-package">
      <div class="discount-tips">限时折扣</div>
      <el-table
        v-if="packages.name"
        ref="rightsTable"
        :data="rights"
        class="rights-table"
        stripe
        style="width:100%"
        max-height="220px">
        <el-table-column
          align="center"
          header-align="center"
          prop="name"
          label="功能特权">
        </el-table-column>
        <el-table-column
          align="center"
          header-align="center"
          prop="name">
          <template #header>
            <svg-icon iconClass="uvip" />
            非VIP
          </template>
          <template slot-scope="scope">
            <svg-icon v-if="scope.row.c_rule_desc == 'x'||scope.row.c_rule_desc == '×'" iconClass="no-rights" />
            <span v-else>{{ scope.row.c_rule_desc }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          header-align="center"
          class-name="table-vip-td"
          label-class-name="table-vip-header"
          prop="name">
          <template slot="header">
            <svg-icon iconClass="vip" />
            {{packages.name}}
          </template>
          <template slot-scope="scope">
            <svg-icon v-if="scope.row.rule_desc == '√'" iconClass="has-rights" />
            <span v-else>{{ scope.row.rule_desc }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div class="time-limit">
        <div class="time-item"
          :class="{'checked': selectedProduct.id === item.id}"
          v-for="item in products"
          :key="item.id"
          @click="setProductItem(item)">
          <h5 class="time has-line">{{ item.name }}</h5>
          <div class="price"><span class="mark">￥</span>{{item.price|moneyToyuan}} <span class="origin-price mark">￥{{ item.origin_price|moneyToyuan }}</span></div>
          <div class="monthly-price">{{item.monthly}}</div>
        </div>
      </div>
    </div>
    <div class="member-order">
      <span class="order-title title">
        订单详情
        <span class="agreement" @click="openUrl">《会员服务协议》</span>
      </span>
      <div class="detail-wrap">
        <div class="pay-way">
          <h5 class="has-line">请选择支付方式</h5>
          <span class="wx way"
            :class="{'checked': payWay === 2}"
            @click="payWay = 2">
            <svg-icon iconClass="wechat" />
            微信
          </span>
          <span class="ali way"
            :class="{'checked': payWay === 1}"
            @click="payWay = 1">
            <svg-icon iconClass="alipay" />
            支付宝
          </span>
        </div>
        <div class="split-line"></div>
        <div class="detail-right">
          <div class="coupon-box">
            <span class="coupon-label">优惠券</span>
            <el-select size="mini" v-model="coupon_id" popper-class="coupon-popper" placeholder="不使用优惠券" no-data-text="暂无可用优惠券" @change="onCouponChange">
              <el-option v-for="item in usageCouponList"
                :key="item.c_id"
                :value="item.c_id"
                :label="couponLabel(item)"></el-option>
            </el-select>
            <span class="receive-coupon" v-if="isShowCoupon" @click="toCouponPage">去领券</span>
          </div>
          <div class="pay-money">
            <div class="price-wrap">
              <span class="mark">￥</span>
              <span class="price">{{ productPrice|moneyToyuan}}</span>
              <span class="discount" v-if="discount>0">已优惠：￥{{discount|moneyToyuan}}</span>
            </div>
            <el-button class="btn-h36 btn-w110 has-radius"
              type="success"
              :loading="payLoading"
              @click.stop="doPay">立即支付</el-button>
          </div>
        </div>
      </div>
    </div>
    <PayCodeDialog :visible.sync="showPayDialog"
      :price="productPrice"
      :payWay="payWay"
      :orderInfo="orderInfo"
      @onPaySucces="onPaySucces"
      @close="onPayClose"/>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import { isPassVersion } from '@/utils/judge'
import { getProducts } from '@/api/rights'
import { createOrder } from '@/api/order'
import { getUsageCouponList } from '@/api/coupon'
import PayCodeDialog from './components/pay-code-dialog.vue'
export default {
  name: 'Pay',
  components: {
    PayCodeDialog
  },
  data () {
    return {
      isShowCoupon: false,
      selectedProduct: {},
      // 权益包
      packages: {},
      rights: [
      ],
      couponList: [],
      // 会员套餐
      products: [],
      selectCoupon: {},
      coupon_id: null,
      // 1 支付宝 2 微信
      payWay: 2,
      payLoading: false,
      showPayDialog: false,
      orderInfo: {}
    }
  },
  computed: {
    ...mapGetters(['appInfo', 'appCfg']),
    usageCouponList () {
      return this.couponList.filter(item => item.threshold <= this.selectedProduct.price)
    },
    discount () {
      if (!this.selectedProduct.id) return 0
      const selectedProduct = this.selectedProduct
      const cdiscount = this.selectCoupon.amount || 0
      const discount = selectedProduct.discount + cdiscount
      if (discount >= selectedProduct.origin_price) {
        return selectedProduct.origin_price - 1
      } else {
        return discount
      }
    },
    productPrice () {
      return this.selectedProduct.origin_price - this.discount
    }
  },
  watch: {
    usageCouponList (val) {
      this.selectCoupon = val[0] || {}
      this.coupon_id = this.selectCoupon.c_id || null
    }
  },
  filters: {
    moneyToyuan (val = 0) {
      return parseFloat((val / 100).toFixed(2))
    },
    valToFixed2 (val = 0) {
      return (val / 100).toFixed(2)
    }
  },
  created () {
    this.pkgId = this.$route.query.pkgid || '10000'
    this.isShowCoupon = isPassVersion('3.1.0.13')
    this.getPackage()
    this.getCouponList()
  },
  mounted () {
    this.$nextTick(() => {
      this.$xz('xz_page_load_finished', 'XZDesktopOrderVIP')
    })
  },
  methods: {
    couponLabel (item) {
      return `￥${this.$options.filters.moneyToyuan(item.amount)}-${item.name}（满￥${this.$options.filters.moneyToyuan(item.threshold)}可用）`
    },
    getCouponList () {
      getUsageCouponList({ p_id: this.pkgId }).then(res => {
        this.couponList = res.data.list || []
      })
    },
    openUrl () {
      this.$xz('xz_open_url', `${this.appCfg.site}/vip-protocol.html`)
    },
    getPackage () {
      const params = { pkg_id: this.pkgId }
      getProducts(params).then(res => {
        const data = res.data || {}
        const packages = res.data.package_list[0]
        let name = packages.name.split('权益包')[0]
        if (!name.includes('VIP')) name = name + 'VIP'
        packages.name = name
        const list = (data.list || []).map(item => {
          let str = ''
          if (item.unlimited) {
            str = '永久使用'
          } else {
            const days = Math.round(item.bus_ext.duration / (24 * 60)) || 1
            if (days < 31) {
              const dayly = item.price / 100 / days
              str = `低至￥${parseFloat(dayly.toFixed(2))}/天`
            } else {
              const month = Math.round(days / 30.5)
              const monthly = item.price / 100 / month
              str = `低至￥${parseFloat(monthly.toFixed(2))}/月`
            }
          }
          item.discount = item.origin_price - item.price
          item.monthly = str
          return item
        })
        this.products = list
        this.setProductItem(this.products[0] || {})
        this.packages = { id: packages.id, name: packages.name }
        this.$nextTick(() => {
          this.$refs.rightsTable.doLayout()
        })
        this.rights = (packages.rights || []).filter(item => {
          return isPassVersion(item.min_ver)
        })
      })
    },
    setProductItem (item) {
      this.selectedProduct = item
    },
    doPay () {
      if (this.payLoading || this.showPayDialog || !this.selectedProduct.id) return // 防抖
      const params = {
        product_id: [this.selectedProduct.id],
        pay_way: this.payWay,
        pay_entry: 'web',
        channel_id: this.appInfo.channel,
        coupon_id: this.coupon_id
      }
      this.payLoading = true
      createOrder(params).then(res => {
        const data = res.data || {}
        this.orderInfo = {
          type: data.pay_way_str,
          orderid: data.order_id,
          sign: data.sign,
          title: data.title,
          appID: process.env.VUE_APP_ID,
          appSecret: process.env.VUE_APP_SECRET
        }
        this.showPayDialog = true
      }).finally(() => {
        this.payLoading = false
      })
    },
    async onPaySucces () {
      await this.$xzAsy('xz_get_stat_id').then(res => {
        if (/^8\d{3}$/.test(res) || !res) {
          const obj = {
            '10000': '9001',
            '20000': '9004',
            '40000': '9102'
          }
          const actionId = (res || 8002) + obj[this.pkgId]
          this.$xz('xz_substat_action', parseInt(actionId))
        } else {
          this.$xz('xz_substat_action', res)
        }
      })
      if (isPassVersion('3.0.2')) {
        this.$xz('xz_switch_dialog', 'XZDesktopOrderVIPSuccess', true, JSON.stringify({ pkgid: this.pkgId }))
      } else {
        this.$xz('xz_switch_dialog', 'XZDesktopOrderVIPSuccess', true)
      }
      this.$xz('xz_update_pay_result', true)
      this.$xz('xz_switch_dialog', 'XZDesktopOrderVIP', false)
    },
    onPayClose () {
      if (this.coupon_id) {
        const index = this.couponList.findIndex(item => item.c_id === this.coupon_id)
        if (index !== -1) {
          this.couponList.splice(index, 1)
        } else {
          this.coupon_id = null
          this.selectCoupon = {}
        }
      }
    },
    toCouponPage () {
      this.$xz('xz_switch_dialog', 'XZMainWindow', true)
      this.$xz('xz_switch_tab', 3)
      this.$xz('xz_switch_dialog', 'XZDesktopOrderVIP', false)
    },
    onCouponChange (val) {
      this.selectCoupon = this.usageCouponList.find(item => item.c_id === val) || {}
    }
  }
}
</script>

<style lang="scss" scoped>
.member-container {
  width: 100%;
  height: 100%;
  padding: 25px 40px 18px;
  background-color: #34353b;
  font-family: "Microsoft YaHei";
  font-size: 14px;
  color: #fff;
}
.title {
  display: flex;
  align-items: center;
  position: relative;
  margin-bottom: 12px;
  height: 21px;
  width: 100%;
  line-height: 21px;
  font-weight: bold;
  font-size: 16px;
  &::before {
    content: "";
    display: inline-block;
    margin-right: 8px;
    width: 6px;
    height: 17px;
    background-color: #00bbd7;
    opacity: 0.3;
    border-radius: 83px;
  }
}
.price {
  font-size: 24px;
  font-weight: bold;
  .mark {
    font-size: 14px;
    font-family: "Microsoft YaHei";
    font-weight: 400;
  }
  .origin-price {
    text-decoration: line-through;
    color: #ad9e79;
  }
}
.member-package {
  position: relative;
  .discount-tips{
    position: absolute;
    z-index: 1;
    top: -10px;
    right: 0;
    width: 57px;
    height: 20px;
    line-height: 20px;
    background: linear-gradient(180deg, #ff6d80 0%, #ff4e4e 100%);
    box-shadow: 0px 0px 4px rgba(255, 0, 0, 0.1);
    border-radius: 0 6px;
    text-align: center;
    font-size: 12px;
    color: #fff;
    font-weight: 400;
  }
  .time-limit {
    display: flex;
    margin-top: 16px;
  }
  .time-item {
    position: relative;
    text-align: center;
    box-sizing: border-box;
    flex-grow: 1;
    height: 90px;
    max-width: 50%;
    padding-top: 8px;
    background: rgba(255, 255, 255, 0.05);
    border: 1px solid #796c4c;
    border-radius: 6px;
    font-size: 14px;
    color: #f8de9d;
    margin-right: 12px;
    &:last-child{
       margin-right: 0;
    }
    cursor: pointer;
    .monthly-price{
      font-size: 12px;
      border-top: 1px solid rgba(121, 108, 76, .5);
      padding-top: 5px;
    }
    &:hover {
      border-color: #2fc670;
    }
    &.checked {
      border-color: #f8de9d;
      background: linear-gradient(180deg, #f7e5b9 0%, #edc666 100%);
      border-radius: 6px 6px 4px;
      color: #9f760f;
      .time {
        &::before,
        &::after {
          background: rgba(159, 118, 15, 0.44);
        }
      }
      .monthly-price{
        border-color: #E2BE68;
      }
    }
  }
}
.has-line {
      display: flex;
      align-items: center;
      justify-content: center;
      font-weight: bold;
      &::before,
      &::after {
        content: "";
        display: inline-block;
        width: 8px;
        height: 1px;
        background: rgba(255, 255, 255, 0.1);
      }
      &::before {
        margin-right: 8px;
      }
      &::after {
        margin-left: 8px;
      }
    }
.member-order {
  margin-top: 16px;
  .order-title {
    position: relative;
    &::before {
      background-color: #ffb302;
    }
    .agreement {
      position: absolute;
      right: 0;
      font-size: 12px;
      font-weight: 400;
      color: #fff;
      opacity: 0.8;
      cursor: pointer;
      &:hover {
        color: #31b068;
        opacity: 1;
      }
    }
  }
  .detail-wrap {
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: relative;
    width: 100%;
    height: 110px;
    background-color: rgba(255, 255, 255, 0.05);
    border: 1px solid #796C4C;
    border-radius: 6px;
  }
  .pay-way {
    width: 190px;
    padding: 17px 0;
    text-align: right;
    .svg-icon {
      font-size: 20px;
      margin-right: 4px;
    }
    .way {
      position: relative;
      display: inline-flex;
      justify-content: center;
      align-items: center;
      width: 80px;
      height: 34px;
      background: rgba(255, 255, 255, 0.1);
      border-radius: 4px;
      margin-top: 17px;
      font-size: 12px;
      cursor: pointer;
      &:hover {
        background: rgba(255, 255, 255, 0.2);
      }
      &.wx {
        margin-right: 10px;
        &.checked {
          background: #2fc670;
          .svg-icon {
            color: #fff;
          }
        }
        .svg-icon {
          color: #44b820;
        }
      }
      &.ali {
        &.checked {
          background: #4c9aff;
          .svg-icon {
            color: #fff;
          }
        }
        .svg-icon {
          color: #4c9aff;
        }
      }
    }
  }
  .split-line{
    flex-basis: 16px;
    height: 100%;
    background-image: linear-gradient(
      transparent 0%,
      transparent 50%,
      #796C4C 50%,
      #796C4C 100%
    );
    background-position: center;
    background-size: 1px 10px;
    background-repeat: repeat-y;
    &::before,&::after{
      content: ' ';
      position: absolute;
      display: inline-block;
      width: 16px;
      height: 8px;
      background-color: #34353B;
      border: 1px solid #796C4C;
    }
    &::before{
      top: -1px;
      border-radius: 0 0 50% 50%/0 0 100% 100%;
      border-top: none;
    }
    &::after{
      bottom: -1px;
      border-radius: 50% 50% 0 0/100% 100% 0 0;
      border-bottom: none;
    }
  }
  .detail-right{
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: 100%;
    padding: 15px 15px 12px;
  }
  .coupon-box{
    .coupon-label{
      margin-right: 5px;
      font-size: 12px;
      color: rgba(255, 255, 255, 0.7);
    }
    .el-select{
      width: 200px;
    }
    .receive-coupon{
      margin-left: 12px;
      font-size: 12px;
      color: #F1D288;
      cursor: pointer;
      &:hover{
        text-decoration: underline;
      }
    }
  }
  .pay-money {
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
    .price-wrap {
      text-align: center;
    }
    .price {
      font-size: 28px;
      color: #fc5b42;
    }
    .mark {
      color: #fc5b42;
      font-size: 16px;
    }
    .discount {
      margin-left: 10px;
      font-size: 12px;
      color: #fff;
      opacity: 0.7;
    }
  }
}
</style>
<style lang="scss">
.rights-table{
  border-radius: 6px;
  tbody .cell{
    line-height: 36px;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 36px;
    .svg-icon{
      font-size: 24px;
    }
  }
  th{
    font-size: 14px;
    background: linear-gradient(180deg, #494949 0%, #222222 100%);
    border-radius: 10px 10px 0px 0px;
    &.table-vip-header,&:last-child{
      border-right:0;
      background: linear-gradient(180deg, #f7e5b9 0%, #edc666 100%);
      color: #9f760f;
    }
    .cell{
      padding: 8px 0;
    }
  }
  .table-vip-td{
    color: #f8de9d;
  }
  th,td{
    border-right: 1px solid rgba(255, 255, 255, 0.06);
    &:last-child{
      border-right: 0
    }
  }
  thead{
    .svg-icon{
      font-size: 24px;
      margin-right: 4px;
      margin-bottom: -2px;
      margin-top: -3px;
    }
  }
  tbody tr {
    background-color: rgba(255, 255, 255, 0.1);
  }
}
.coupon-popper{
  .el-select-dropdown__wrap{
    max-height: 80px;
  }
  .el-select-dropdown__item{
    max-width: 200px;
  }
  .el-scrollbar__bar{
    opacity: 1;
  }
}
</style>
